'''
Created on Oct 23, 2011

@author: baiamc
'''

from blackjack.card import Card

class Hand(object):
    '''
    Hand class for blackjack game
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self.cards = []
        
    def value(self):
        '''
        Return the blackjack value of a hand of cards
        '''
        aces = 0
        total = 0
        for card in self.cards:
            # Count up the value of the cards.  Save the number of aces for later.
            if card.number == 1:
                aces+=1
            elif card.number > 10:
                total += 10
            else:
                total += card.number
        # Figure out the aces
        if aces > 1:
            total += aces - 1
        if aces > 0:
            if total < 10:
                total += 11
            else:
                total += 1
        
        return total
    
    def add(self,card):
        ''' 
        Add a card to the hand
        
        Raises an InvalidCardError if the argument isn't a card
        '''
        
        if isinstance(card,Card):
            self.cards.append(card)
        else:
            raise InvalidCardError(card)
    
    def split(self,second_hand):
        '''
        Splits a hand if it's eligible to be split.
        
        Hand must have only two cards, and the cards must have the same face value.
        Removes one of the cards from the current hand, adds it to a new second hand,
        and returns the new hand as a parameter.
        
        Returns True if the split succeeded and False otherwise
        '''
        
        if len(self.cards) == 2 and self.cards[1].number == self.cards[2].number:
            second_hand=Hand()
            second_hand.add(self.cards.pop())
            
            return True
        return False
    
    def display(self):
        '''
        Display all cards in a hand
        '''
        
        for card in self.cards:
            card.display()
            
        
        
    
class InvalidCardError(Exception):
    '''
    Error raised for invalid card objects.
    
    Returns the object that was not a valid card
    '''
    
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return repr(self.value)
        
        
    
        
        
                
            
            
        